package com.qs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qs.mapper.FormFieldMapper;
import com.qs.mapper.FormMapper;
import com.qs.mapper.entity.Form;
import com.qs.mapper.entity.FormField;
import com.qs.service.FormFieldService;
import com.qs.service.FormService;
import com.qs.service.bo.FormFieldBO;
import com.qs.util.BeanCopyUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class FormFieldServiceImpl extends ServiceImpl<FormFieldMapper, FormField> implements FormFieldService {
    private final FormMapper formMapper;

    @Override
    public List<FormFieldBO> getFormFieldByFormName(String formName) {
        // 查询表单名
        LambdaQueryWrapper<Form> formLambdaQueryWrapper = Wrappers.lambdaQuery();
        formLambdaQueryWrapper.eq(Form::getName, formName);
        Form form = formMapper.selectOne(formLambdaQueryWrapper);
        LambdaQueryWrapper<FormField> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(FormField::getFormId, form.getId());
        List<FormField> formFieldList = baseMapper.selectList(lambdaQueryWrapper);
        return BeanCopyUtils.copyBeanList(formFieldList, FormFieldBO.class);
    }

    @Override
    public List<FormFieldBO> getFormFieldByFormId(Long formId) {
        LambdaQueryWrapper<FormField> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(FormField::getFormId, formId).orderByAsc(FormField::getSort).orderByAsc(FormField::getCreateTime);
        List<FormField> formFieldList = baseMapper.selectList(lambdaQueryWrapper);
        return BeanCopyUtils.copyBeanList(formFieldList, FormFieldBO.class);
    }

    @Override
    public String add(FormFieldBO formFieldBO) {
        FormField formField = BeanCopyUtils.copyBean(formFieldBO, FormField.class);
        isExist(FormField::getName, formField.getName(), formField.getFormId());
        boolean saved = save(formField);
        return saved ? "新增成功" : "新增失败";
    }

    @Override
    public String edit(FormFieldBO formFieldBO) {
        FormField formField = BeanCopyUtils.copyBean(formFieldBO, FormField.class);
        boolean updated = updateById(formField);
        return updated ? "修改成功" : "修改失败";
    }

    private void isExist(SFunction<FormField, ?> column, Object value, Long formId) {
        LambdaQueryWrapper<FormField> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(column, value).eq(FormField::getFormId, formId);
        FormField formField = getOne(queryWrapper);
        if (Objects.nonNull(formField)) {
            throw new RuntimeException("字段已存在");
        }
    }
}
